import { login, getProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

export default {
  namespaced: true,
  state: {
    token: getToken() || null,
    setUserInfo: {} // 默认为null
  },
  // 修改状态
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken // 设置token
      setToken(newToken)
    },
    // 删除token
    removeToken(state) {
      state.token = null // 删除vuex的token
      removeToken()
    },
    setUserInfo(state, newInfo) {
      state.setUserInfo = newInfo
    },
    removeUserInfo(state) {
      state.setUserInfo = {}
      // 如果设置为null也会报错
    }
  },
  actions: {
    async getUserprofile(contnext, newValue) {
      try {
        const res = await getProfile()
        console.log(res)
        const rs = await getUserDetailById(res.data.userId)
        console.log(rs)
        contnext.commit('setUserInfo', { ...res.data, ...rs.data })
        console.log(rs)
      } catch (error) {
        console.log(error)
      }
    },
    async getUsertoken(contnext, newValue) {
      try {
        const res = await login(newValue)
        console.log(res)
        contnext.commit('setToken', res.data)
      } catch (err) {
        console.log(err)
      }
    },
    async userLogout(context) {
      context.commit('removeUserInfo')
      context.commit('removeToken')
    }
  }
}

